<template>
	<view>
		<view class="container" :style="'padding-top: ' + (navbar.top + navbar.height + 58) + 'px'">
			<view class="navbar" :style="'height: ' + (navbar.top + navbar.height + 59) + 'px;'">
				<view class="inner" :style="'height: ' + (navbar.top + navbar.height + 9) + 'px;'">
					<!-- #ifdef MP-WEIXIN -->
					<view class="search_box"
						:style="'top:' + navbar.top + 'px;height: ' + navbar.height + 'px;width:'+(navbar.customWidth?navbar.customWidth:267)+'px;left:'+(navbar.marginLeft?navbar.marginLeft:17)+'px;'">
						<!-- 扫一扫 -->
						<view class="scan" @tap="mesClick">
							<view class="label" @tap="goxuqiu">
								<van-icon size="20px" color="#fff" name="wap-nav" />
							</view>
						</view>

						<!-- 搜索 -->
						<view class="search" :class="!navbar.customWidth?'wx_search':''"
							:style="'padding: ' + (navbar.height - 24) / 2 + 'px;'" @tap="visitSearch">
							<van-search readonly custom-class="search-round" placeholder="请输入您要搜索的内容"
								background="#f4f4f4" placeholder-style="font-size:24rpx" shape="round" />
						</view>
					</view>
					<!-- #endif -->
				</view>
				<view class="tab_box">
					<view class="tab_line_poa">
						<view class="tab_line"></view>
					</view>

					<view class="tab_tab">
						<view class="kj_tabs">
							<view class="kj_tab" v-for="(tab,index) in tabs" :key="index">
								<view @click="handleTabs(tab)">
									{{tab.text}}
									<view class="tab_botline" :class="tabsActive!=tab.text?'line_show':''"></view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<block v-if="loading == 1">
				<!-- 圆形点击框 -->
				<view class="round-click van-icon van-icon-edit">
					<van-icon name="/static/images/fabu.png" size="26" color="#fff" @click="fabu" />
				</view>
				<view class="content">
					<view class="left">
						<block v-for="(item, index) in goodsList" :key="index">
							<block name="item" v-if="(index % 2) == 0">
								<view class="item">
									<image :class="'item-img ' + (imgheightsUser[item.id] ? 'zindex' : '')"
										@tap="goxuqiudetail" :data-id="item.id"
										:src="$com.getUrlSuffix(item.picurl) != 'mp4' ? $com.imageOSS(item.picurl) : $com.imageOSS(item.picurl) + '?x-oss-process=video/snapshot,t_3000,f_jpg,m_fast'"
										:mode="imgheightsUser[item.id] ? 'aspectFill' : 'widthFix'"
										@load="imageLoadUser">
									</image>
									<view class="item-title-box" @tap="goxuqiudetail" :data-id="item.id">
										<view class="item-title">{{ item.title }}</view>
									</view>
									<view class="name">
										<image class="item-ava" :src="$com.imageOSS(item.headurl)"></image>
										<text class="name-title">{{ item.nickname }}</text>
										<view class="heart" @tap.stop.prevent="followClick" :data-xqid="id">
											<van-icon :name="item.is_like ? 'like' : 'like-o'" size="32rpx"
												:color="item.is_like ? '#f53a42' : '#999999'" style="margin-right: 6rpx" />
											<text>{{ item.likes_num }}</text>
										</view>
									</view>
								</view>
							</block>
						</block>
					</view>
					<view class="right">
						<block v-for="(item, index) in goodsList" :key="index">
							<block name="item" v-if="(index % 2) == 1">
								<view class="item">
									<image :class="'item-img ' + (imgheightsUser[item.id] ? 'zindex' : '')"
										@tap="goxuqiudetail" :data-id="item.id" :src="$com.getUrlSuffix(item.picurl) != 'mp4' ?
										$com.imageOSS(item.picurl) :
										$com.imageOSS(item.picurl) + 
										'?x-oss-process=video/snapshot,t_3000,f_jpg,m_fast'"
										:mode="imgheightsUser[item.id] ? 'aspectFill' : 'widthFix'"
										@load="imageLoadUser"></image>
									<view class="item-title-box" @tap="goxuqiudetail" :data-id="item.id">
										<view class="item-title">{{ item.title }}</view>
									</view>
									<view class="name">
										<image class="item-ava" :src="$com.imageOSS(item.headurl)"></image>
										<text class="name-title">{{ item.nickname }}</text>
										<view class="heart" @tap.stop.prevent="followClick" :data-xqid="item.id">
											<van-icon :name="item.is_like ? 'like' : 'like-o'" size="32rpx"
												:color="item.is_like ? '#f53a42' : '#999999'"
												style="margin-right: 6rpx" />
											<text>{{ item.likes_num }}</text>
										</view>
									</view>
								</view>
							</block>
						</block>
					</view>
					<!-- 加载loading -->
					<kj-loading ref="kjLoading" :loadmore="loadmore" :loaddone="loaddone"></kj-loading>
				</view>
			</block>
		</view>
		<tab-bar ref="tabbar" :tabInd="2" :number="number" :v_count="v_count"></tab-bar>
	</view>
</template>
<script>
	import {
		getImage,
		getPage,
		getTabbar
	} from '../../utils/config';
	import api from '../../utils/api';
	import {
		http,
		storage,
		promisify,
		$toast,
		$loading,
		$query
	} from '../../utils/utils';
	import wxApi from '../../utils/wxApi';
	import {
		headerInfo
	} from '../../utils/env';
	const app = getApp();
	let {
		height,
		right,
		menuWidth
	} = headerInfo
	let leftStyle = `right: ${menuWidth / 2 / 2 + right}px`
	let tipTopStyle = `top: ${height}px;`
	let topStyle = `top: ${height + 10}px;`
	export default {
		data() {
			return {
				getImage: getImage,
				getPage: getPage,
				logged: 0,
				loading: 0,
				userId: 0,

				navbar: {
					top: '',
					height: '',
					right: 0,
					width: ''
				},

				window: {
					windowWidth: 0
				},

				hfListIndex: 0,
				botZtListIndex: 0,
				timesHours: 0,
				guize: {},
				city: '',
				timesMinute: 0,
				timesSecond: 0,
				goodsNavFix: false,
				goodsNavType: 1,
				goodsList: [],
				goodsListPage: 1,
				goodsListPages: 0,
				loadmore: true,
				loaddone: false,
				popupShow: false,
				popupShow1: false,
				popupShowTip: false,
				showwellcome: false,
				tipTopStyle: tipTopStyle,
				leftStyle: leftStyle,
				topStyle: topStyle,
				imgheights: {},
				imgheightsUser: {},
				curBannerHeight: 0,
				value1: 0,
				option1: [],
				cid: 0,
				crossAxisCount: 2,
				crossAxisGap: 8,
				mainAxisGap: 8,
				myTime: null,
				tabsActive: '推荐',
				orders: 1,
				swiper: '',
				selected: 0,
				number: 0,
				dots: '',
				id: '',
				title: '',
				nickname: '',
				is_like: false,
				likes_num: 0,
				data: '',
				tabs: [{
						id: 1,
						text: '推荐'
					},
					{
						id: '',
						text: '发现'
					}
				],
				v_count:0,
				socket:null
			};
		}
		/**
		 * 生命周期函数--监听页面加载
		 */
		,
		onLoad(options) {
			//获取用户登录
			app.globalData
				.getLogin()
				.then((res) => {
					const {
						user
					} = res.data;
					this.userId = user.user_id
					this.logged = res.code
				})
				.catch((res) => {
					this.logged = res
					// this.goLogin();
				});
			//获取system信息
			promisify(uni.getSystemInfo)().then((res) => {
				//获取右上角胶囊信息
				// #ifdef MP-WEIXIN
				this.navbar = uni.getMenuButtonBoundingClientRect()
				console.log("--------------", this.navbar)
				// #endif

				//获取右上角胶囊信息
				// #ifdef MP-TOUTIAO
				let navbar = uni.getMenuButtonBoundingClientRect()
				let CustomButton = tt.getCustomButtonBoundingClientRect()
				navbar.customWidth = CustomButton.customNavigation.width - 10
				navbar.marginLeft = CustomButton.customNavigation.marginLeft + 5
				this.navbar = navbar
				// #endif

				// #ifdef APP-PLUS
				this.navbar = menuButton
				// #endif
				this.window = res
			});
			if (this.city == '') {
				this.city = app.globalData.zone.shortname
			}
			//第一部分数据加载
			http.post(
				api.default, {
					data: {
						action: 'getadsbanner',
						type: 6
					}
				},
				false
			).then((res) => {
				const {
					data
				} = res.data;
				console.log(res.data);
				this.swiper = data
				this.loading = 1
			});
			http.post(
				api.default, {
					data: {
						action: 'getcategoryoption'
					}
				},
				false
			).then((res) => {
				const {
					data
				} = res.data;
				//console.log(res.data);
				this.option1 = res.data.data
			});
			setTimeout(() => {
				//加载产品列表
				this.getProductsInfo((res) => {
					console.log(res);
					this.goodsList = res.list
					this.loadmore = false
				});
			}, 1);
		},
		/**
		 * 页面滚动函数--监听页面滚动事件
		 */
		onPageScroll(e) {},
		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady() {},
		/**
		 * 生命周期函数--监听页面显示
		 */
		async onShow() {
			const res = await app.globalData.getLogin();
			const {
				user
			} = res.data;
			this.userId = user.user_id;
			this.v_count = app.globalData.v_count;
			if (this.userId) {
				this.myTime = setInterval(function() {
					this.number = app.globalData.unReadMsg
				}, 5000)
			}
		},
		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide() {
			console.log('user_onHide________清除定时器~');
			clearInterval(this.myTime);
			
			// #ifdef MP-WEIXIN
			console.log('onHide------------');
			uni.closeSocket();
			// #endif
			
			// #ifdef MP-TOUTIAO
			this.socket?.close()
			// #endif
		},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload() {
			console.log('离开页面');
			// #ifdef MP-WEIXIN
			uni.closeSocket();
			// #endif
			
			// #ifdef MP-TOUTIAO
			this.socket?.close()
			// #endif
		},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh() {
			uni.showLoading({
				title: '加载中...'
			});
			this.goodsListPage = 1
			//加载产品列表
			this.getProductsInfo((res) => {
				console.log(res);
				this.goodsList = res.list
				this.loadmore = false
				uni.stopPullDownRefresh();
				uni.hideLoading();
			});
		},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom() {
			let {
				goodsListPage,
				goodsListPages,
				loadmore
			} = this;
			//未请求完且未在加载中
			if (goodsListPages > goodsListPage && !loadmore) {
				goodsListPage++;
				loadmore = true;

				//显示加载效果
				this.goodsListPage = goodsListPage
				this.loadmore = loadmore
				uni.showNavigationBarLoading();

				//请求数据
				this.getProductsInfo((res) => {
					let {
						goodsList
					} = this;
					loadmore = false;
					this.loadmore = loadmore
					this.goodsList = goodsList.concat(res.list)
					//隐藏加载效果
					uni.hideNavigationBarLoading();
				});
			}
		},
		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage: function() {
			if (this.userId > 0) {
				pageshare += '?pid=' + this.userId;
			}
			return {
				title: ``,
				imageUrl: '',
				path: pageshare,
				success: function(res) {
					console.log('分享');
					//$toast(pageshare);
					if (res.errMsg == 'shareAppMessage:ok') {
						//转发成功
						$toast(pageshare);
						console.log('分享成功');
						if (res.hasOwnProperty('shareTickets')) {
							//分享到群
						} else {
							// 分享到个人
						}
					} else {
						//转发失败
						console.log('分享失败');
					}
				}
			};
		},
		methods: {
			handleTabs(e) {
				let tit = e.text;
				this.tabsActive = tit
				this.orders = tit == '推荐' ? 1 : ''
				this.getProductsInfo((res) => {
					this.goodsList = res.list
					this.loadmore = false
				});
			},
			tabsClick(e) {
				let tit = e.detail.title;
				this.tabsActive = tit
				this.orders = tit == '推荐' ? 1 : ''
				this.getProductsInfo((res) => {
					this.goodsList = res.list
					this.loadmore = false
				});
			},

			goxuqiu() {
				wxApi.navigateTo(getPage.myxuqiu);
			},

			gosheji() {
				wxApi.redirectTo('/pages/designer/home');
			},

			handleNotouch() {
				return false;
			},

			goxuqiudetail(e) {
				const data = e.currentTarget.dataset || e.target.dataset;
				if (data.id) {
					wxApi.navigateTo(getPage.xuqiudetail, {
						id: data.id
					});
				}
			},

			imageLoad: function(e) {
				//获取图片真实宽度
				var imgwidth = e.detail.width;
				var imgheight = e.detail.height;
				var //宽高比
					ratio = imgwidth / imgheight; //计算的高度值
				var viewHeight = 750 / ratio;
				var imgheight = viewHeight;
				var imgheights = this.imgheights;
				//把每一张图片的对应的高度记录到数组里
				imgheights[e.target.dataset.id] = imgheight;
				this.imgheights = imgheights
			},

			imageLoadUser: function(e) {
				console.log('eeeeeeeeeeeee',e)
				//获取图片真实宽度
				var imgwidth = e.detail.width;
				var imgheight = e.detail.height;
				var //宽高比
					ratio = imgwidth / imgheight;
				let bol = ratio > 1 ? true : false;
				var imgheightsUser = this.imgheightsUser;
				imgheightsUser[e.target.dataset.id] = bol;
				this.imgheightsUser = imgheightsUser;
				this.$forceUpdate()
				console.log('e.target.dataset.id',e.target.dataset.id)
				console.log('imgheightsUser',this.imgheightsUser)
			},

			updateDot(data) {
				let dots = data.detail.dots;
				this.dots = dots
			},

			mesClick(e) {
				wxApi.navigateTo('/pages/location/index');
			},

			/**
			 * swiper 记录当前值
			 */
			hfListChange(e) {
				this.hfListIndex = e.detail.current
			},

			botZtListChange(e) {
				this.botZtListIndex = e.detail.current
			},

			/**
			 * 搜索
			 */
			visitSearch() {
				wxApi.navigateTo(getPage.searchfabu);
			},

			golink(e) {
				const data = e.currentTarget.dataset || e.target.dataset;
				console.log(data.url);
				//转为小写并去除左右空格
				var str = data.url.toLowerCase();
				if (str != '') {
					if (str.indexOf('https') === 0 || str.indexOf('http') === 0) {
						wxApi.navigateTo('/pages/web/web?id=' + str);
					} else if (str.indexOf('za://') == 0) {
						console.log(str);
						var array = str.split('_');
						console.log(array);
						if (array[0].replace('za://', '') == 'column') {
							app.globalData.g_cid = array[1];
							uni.switchTab({
								url: getPage.column
							});
						}
					} else {
						wxApi.navigateTo('/pages/goods/goods?id=' + str);
					}
				}
			},

			/**
			 * 禁止手动滑动
			 */
			noSwiping() {
				return false;
			},

			oncategorychange(e) {
				this.cid = e.detail
				this.goodsListPage = 1
				//加载产品列表
				this.getProductsInfo((res) => {
					console.log(res);
					this.goodsList = res.list
					this.loadmore = false
				});
			},

			/**
			 * 获取产品数据
			 */
			getProductsInfo(cb, a = false) {
				let {
					goodsNavType,
					goodsListPage,
					goodsListPages,
					cid,
					loaddone,
					userId,
					orders
				} = this;
				var latitude = 0;
				var longitude = 0;
				var mylocation = null;
				if (uni.getStorageSync('mylocation') == '' && app.globalData.zone == null) {
					wxApi.navigateTo('/pages/location/index');
					return;
				} else if (uni.getStorageSync('mylocation') != '') {
					mylocation = JSON.parse(uni.getStorageSync('mylocation'));
					latitude = mylocation.latitude;
					longitude = mylocation.longitude;
				} else {
					latitude = app.globalData.zone.lat;
					longitude = app.globalData.zone.lng;
				}
				http.post(
					api.default, {
						data: {
							action: 'getxuqiulist',
							userid: userId,
							pagesize: 20,
							pageindex: goodsListPage,
							cid: cid,
							latitude: latitude,
							longitude: longitude,
							orders
						}
					},
					a
				).then((res) => {
					const {
						data
					} = res.data;
					//是否加载完毕
					if (goodsListPage == data.pages) {
						loaddone = true;
					}
					this.goodsListPages = data.pages
					this.loaddone = loaddone
					if (cb) {
						cb(data);
					}
				});
			},

			fabu() {
				wxApi.navigateTo(getPage.fabuxuqiu);
			},

			/**
			 * 跳转登录
			 */
			goLogin() {
				wxApi.setStartPage();
				wxApi.navigateTo(getPage.login);
			},

			/**
			 * 关注店铺
			 */
			followClick(event) {
				let {
					xqid
				} = event.currentTarget.dataset;
				var {
					logged,
					userId
				} = this;
				console.log('logged', logged);
				if (logged) {
					http.post(api.default, {
						data: {
							action: 'like_xuqiu',
							userid: userId,
							id: xqid
						}
					}).then((res) => {
						let {
							errmsg,
							data
						} = res.data;
						$toast(errmsg, {
							icon: 'success'
						});
						// 前端显示跟新收藏状态
						let goodsArr = this.goodsList;
						goodsArr.forEach((item) => {
							if (item.id == xqid) {
								item.is_like = data;
								item.likes_num = data ? item.likes_num + 1 : item.likes_num - 1;
							}
						});
						this.goodsList = goodsArr
					});
				} else {
					this.goLogin();
				}
			}
		}
	};
</script>
<style>
	@import './xqlist.css';
</style>
